<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'"
             width='662px'
             class="addWxbanner"
             :close-on-click-modal="false"
             :visible.sync="visible">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="优先级"
                    prop="priority">
        <el-input v-model="dataForm.priority"
                  placeholder="优先级"></el-input>
        <!-- <el-input-number v-model="dataForm.priority"
                         controls-position="right"
                         @change="handleChange"
                         :min="1"
                         width="180px"
                         :max="10"></el-input-number> -->
      </el-form-item>
      <el-form-item label="轮播图"
                    prop="image">
        <!-- <el-input v-model="dataForm.image"
                  placeholder="轮播图"></el-input> -->
        <el-upload class="avatar-uploader"
                   :action="action"
                   name="file"
                   :headers='headers'
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.image"
               :src="dataForm.image"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
          <div slot="tip"
               class="el-upload__tip">只能上传jpg/png/gif文件，图片宽高请固定为375px/163px，且不超过200kb</div>
        </el-upload>
      </el-form-item>
      <!-- <el-form-item label="跳转地址"
                    prop="jumpUrl">
        <el-input v-model="dataForm.jumpUrl"
                  placeholder="跳转地址"></el-input>
      </el-form-item> -->
      <el-form-item label="创建时间"
                    prop="createTime">
        <el-date-picker v-model="dataForm.createTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="删除时间"
                    prop="deleteTime">
        <el-date-picker v-model="dataForm.deleteTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择删除时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间"
                    prop="updateTime">
        <el-date-picker v-model="dataForm.updateTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer"
          class="dialog-footer">
      <!-- <el-button @click="visible = false">取消</el-button> -->
      <el-button type="primary"
                 class="btn"
                 @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: 0,
        priority: '',
        image: '',
        jumpUrl: '',
        createTime: '',
        deleteTime: '',
        updateTime: ''
      },
      headers: {
        token: ''
      },
      // 图片上传地址
      action: '',
      dataRule: {
        priority: [
          { required: true, message: '优先级不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 正则校验
              let _reg = /^\d+$/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('只支持数字'))
              }
            }
          }
        ],
        image: [
          { required: true, message: '轮播图不能为空', trigger: 'blur' }
        ]
        // jumpUrl: [
        //   { required: true, message: '跳转地址不能为空', trigger: 'blur' }
        // ],
        // createTime: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ],
        // deleteTime: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ],
        // updateTime: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ]
      }
    }
  },
  created () {
    // /sys/config/upload-img
    this.action = this.$baseUrl + '/sys/config/upload-img'
    this.headers.token = this.$cookie.get('token')
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/sys/wxbanner/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.priority = data.wxBanner.priority
              this.dataForm.image = data.wxBanner.image
              this.dataForm.jumpUrl = data.wxBanner.jumpUrl
              this.dataForm.createTime = data.wxBanner.createTime
              this.dataForm.deleteTime = data.wxBanner.deleteTime
              this.dataForm.updateTime = data.wxBanner.updateTime
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/wxbanner/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'priority': this.dataForm.priority,
              'image': this.dataForm.image,
              'jumpUrl': this.dataForm.jumpUrl,
              'createTime': this.dataForm.createTime,
              'deleteTime': this.dataForm.deleteTime,
              'updateTime': this.dataForm.updateTime
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 图片上传成功处理
    handleAvatarSuccess (res, file) {
      this.dataForm.image = 'http://' + res.url
      // this.dataForm.companyLicense = URL.createObjectURL(file.raw)
      // console.log(file)
      // this.dataForm.companyLicense = uploadImgToBase64(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = (file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif')
      const isLt2M = file.size / 1024 / 1024 < 0.2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG，png，gif 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 200k!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>


<style lang="scss">
.addWxbanner {
  .el-input.el-input--medium {
    width: 370px;
  }
  .el-dialog__header {
    background-color: #f8f8f8;
  }
  .el-dialog__body {
    display: flex;
    justify-content: center;
  }
  .btn {
    width: 370px;
  }
  .dialog-footer {
    text-align: center !important;
    padding-bottom: 39px;
  }
  .el-dialog__footer {
    text-align: center;
    padding-bottom: 39px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
